package com.ycd.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.ycd.domain.Pojo;
import com.ycd.domain.Product;
import com.ycd.domain.Result;
import com.ycd.domain.Store;
import com.ycd.feigns.StoreFeignClient;
import com.ycd.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private IProductService productService;

    @Autowired
    private StoreFeignClient storeFeignClient;

    /**
     * 自定义一个数据-主要做限流-熔断降级操作
     * @return
     */
    @GetMapping("/loadById/{id}")
    @SentinelResource(value="product-loadById", blockHandler = "degradationMethod")
    public Product loadById(@PathVariable("id") Long id) {
        return new Product(id,"短袖","99",50);
    }

    /**
     * 这里做了一个限流操作,响应请求,在sentinel流控定义阈值1秒
     * 1.导入单个sentinel依赖
     * 2.指定sentinel服务端地址
     * 3.将上面定义的数据给响应给浏览器，成功进入sentinel流控定义阈值1秒
     * 4.快速点击请求地址-一秒内多次发送请求，响应错误信息
     */
    public Product degradationMethod(@PathVariable("id") Long id,BlockException e){
        e.printStackTrace();
        return new Product(-1L, "服务限流触发！", "当前服务流量过大，请稍后重试！",1);
    }

    // 完成商品服务的添加接口成功
    @RequestMapping(value="/add", method = RequestMethod.POST)
    public Result add(@RequestBody Product product){
        productService.add(product);
        return new Result();
    }

    // 使用openfegin组件-调用（store）库存服务进行添加
    @RequestMapping(value="/save", method = RequestMethod.POST)
    public Result save(@RequestBody Store store){
        storeFeignClient.save(store);
        return new Result();
    }
}
